package com.example.demo.controller;

import com.example.demo.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/trans")
public class TransController {
    @Autowired
    private DataSourceTransactionManager dataSourceTransactionManager;
    @Autowired
    private TransactionDefinition transactionDefinition;
    @Autowired
    private UserService userService;

    @Transactional //出现运行时发生异常或者error，自动执行事务回滚   没有发生异常或处理异常，正常提交
    @RequestMapping("/r1")
    public Boolean registry(String name, String password) {

        Integer result = userService.insertUser(name, password);
        log.info("数据影响行数： " + result);
        int a = 10/0;
        return true;
    }

    @Transactional(rollbackFor = Exception.class)//所有异常回滚
    @RequestMapping("/r2")
    public Boolean registry2(String name, String password) throws IOException{

        Integer result = userService.insertUser(name, password);
        log.info("数据影响行数： " + result);
        if(true) {
             throw new IOException();
        }
        return true;
    }

    @Transactional
    @RequestMapping("/r3")
    public Boolean registry3(String name, String password) throws IOException{

        Integer result = userService.insertUser(name, password);
        log.info("数据影响行数： " + result);
        if(true) {
            throw new IOException();
        }
        return true;
    }
}
